#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
民法典数据库性能监控工具
"""

from pymongo import MongoClient
import time
import json
from datetime import datetime

def performance_monitor():
    """性能监控"""
    print("=" * 60)
    print("⚡ 民法典数据库性能监控")
    print("=" * 60)
    
    try:
        client = MongoClient("mongodb://localhost:27017/")
        db = client['civil_code_db']
        collection = db['civil_code_articles']
        
        performance_data = {
            "monitor_time": datetime.now().isoformat(),
            "tests": []
        }
        
        # 测试场景
        test_scenarios = [
            {
                "name": "基础查询",
                "query": {},
                "limit": 10
            },
            {
                "name": "条文号查询",
                "query": {"article_number": "第一条"},
                "limit": 1
            },
            {
                "name": "章节查询",
                "query": {"chapter_info.part": "第一编 总则"},
                "limit": 50
            },
            {
                "name": "文本搜索",
                "query": {"$text": {"$search": "民事"}},
                "limit": 20
            },
            {
                "name": "内容搜索",
                "query": {"content": {"$regex": "合法权益"}},
                "limit": 10
            }
        ]
        
        print("📊 性能测试结果:")
        print("   测试场景        | 响应时间 | 结果数")
        print("   " + "-" * 40)
        
        for scenario in test_scenarios:
            name = scenario["name"]
            query = scenario["query"]
            limit = scenario["limit"]
            
            # 执行测试
            start_time = time.time()
            try:
                if "$text" in str(query):
                    results = list(collection.find(query).limit(limit))
                else:
                    results = list(collection.find(query).limit(limit))
                    
                end_time = time.time()
                response_time = (end_time - start_time) * 1000
                result_count = len(results)
                
                print(f"   {name:<15} | {response_time:>6.1f}ms | {result_count:>4}条")
                
                performance_data["tests"].append({
                    "scenario": name,
                    "response_time_ms": response_time,
                    "result_count": result_count,
                    "status": "success"
                })
                
            except Exception as e:
                print(f"   {name:<15} | 失败     | 错误")
                performance_data["tests"].append({
                    "scenario": name,
                    "response_time_ms": 0,
                    "result_count": 0,
                    "status": "error",
                    "error": str(e)
                })
        
        # 数据库统计信息
        print("\n📈 数据库统计:")
        stats = db.command("dbStats")
        print(f"   数据库大小: {stats.get('dataSize', 0) / 1024 / 1024:.1f} MB")
        print(f"   索引大小: {stats.get('indexSize', 0) / 1024 / 1024:.1f} MB")
        print(f"   集合数: {stats.get('collections', 0)}")
        
        performance_data["database_stats"] = {
            "data_size_mb": stats.get('dataSize', 0) / 1024 / 1024,
            "index_size_mb": stats.get('indexSize', 0) / 1024 / 1024,
            "collections": stats.get('collections', 0)
        }
        
        # 保存性能数据
        report_file = f"performance_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        with open(report_file, 'w', encoding='utf-8') as f:
            json.dump(performance_data, f, ensure_ascii=False, indent=2, default=str)
        
        print(f"\n📁 性能报告已保存: {report_file}")
        
        client.close()
        return True
        
    except Exception as e:
        print(f"❌ 性能监控失败: {str(e)}")
        return False

if __name__ == "__main__":
    performance_monitor()
